<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      custom-class="dialogClass"
      @close="$emit('closed')"
    >
      <div slot="title">对接入的应用及模块排序</div>
      <div class="search">
        <el-form ref="Form" :model="Form" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="接入应用集"
                prop="appSetId"
                :rules="[
                  { required: true, message: '请选择接入应用集', trigger: 'change' }
                ]"
              >
                <el-select v-model="Form.appSetId" clearable @change="selectChange">
                  <el-option v-for="(item, index) in appSetList" :key="index" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="已接入应用" prop="appId">
                <el-select v-model="Form.appId" clearable @change="selectChange1">
                  <el-option v-for="(item, index) in appList" :key="index" :label="item.appname" :value="item.appid" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="tableClass">
        <YituTable
          class="tree-table"
          border
          :loading="loading"
          :table-obj="sortObj"
          :data="sortData"
          max-height="500"
        >
          <template #appName="{ customHtmlObj: { row } }">
            <span v-if="sortQueryParams.appId && (flagArr.includes(row.id))">{{ row.appName }}</span>
            <span v-else-if="flagArr.includes(row.id)">{{ row.appName }}</span>
            <span v-else>{{ '' }}</span>
          </template>
          <template #before-table-button="{ beforeTableButton: { row } }">
            <div style="text-align:center">
              <div v-if="sortQueryParams.appId">
                <el-button v-if="!flagArr.includes(row.id) && !firstArr.includes(row.id)" type="text" class="common-btn c-blue" size="mini" @click="move(row, -1)">上移</el-button>
                <el-button v-if="!flagArr.includes(row.id) && !lastArr.includes(row.id)" type="text" class="common-btn c-blue" size="mini" @click="move(row, 1)">下移</el-button>
              </div>
              <div v-else>
                <div v-if="flagArr.includes(row.id)">
                  <el-button v-if="flagArr[0] !== row.id" type="text" class="common-btn" :class="{'c-gray':!ifAuth,'c-blue':ifAuth}" size="mini" :disabled="!ifAuth" @click="move(row, -100)">上移</el-button>
                  <el-button v-if="flagArr[flagArr.length - 1] !== row.id" type="text" class="common-btn" :class="{'c-gray':!ifAuth,'c-blue':ifAuth}" size="mini" :disabled="!ifAuth" @click="move(row, 100)">下移</el-button>
                </div>
                <div v-else>
                  <el-button v-if="!firstArr.includes(row.id) " type="text" class="common-btn c-blue" size="mini" @click="move(row, -1)">上移</el-button>
                  <el-button v-if="!lastArr.includes(row.id) " type="text" class="common-btn c-blue" size="mini" @click="move(row, 1)">下移</el-button>
                </div>
              </div>
            </div>
          </template>
        </YituTable>
      </div>
      <div slot="footer" class="btn-group">
        <el-button type="primary" @click="showDialog">保存</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </div>
    </el-dialog>
    <ConfirmDialog ref="ConfirmDialog" content="确认是否保存" @cancel="$refs.ConfirmDialog.setDialogVisible(false)" @confirm="save" />
  </div>
</template>

<script>
import ConfirmDialog from '@/components/common/ConfirmDialog'
import { sortList, sortAuth, sort, getAppByAppSet } from '@/api/appAndModule/index.js'
export default {
  name: 'SortDialog',
  components: { ConfirmDialog },
  props: {
    appSetList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      sortQueryParams: {
        'appId': '',
        'appSetId': ''
      },
      Form: {
        appId: '',
        appSetId: ''
      },
      sortObj: {
        tableHead: [
          {
            label: '所属应用',
            value: 'appName',
            align: 'left',
            headerAlign: 'left',
            editType: 'custom',
            customName: 'appName'
          },
          {
            label: '所属模块',
            value: 'accessName',
            align: 'left',
            headerAlign: 'left'
          }
        ],
        indexAlign: 'center',
        handleWidth: 148,
        isSelection: false,
        hasEditButton: false,
        isHasIndex: true,
        hasDeleteButton: false
      },
      appList: [],
      sortData: [],
      mergeArr: [],
      flagArr: [],
      firstArr: [],
      lastArr: [],
      dialogVisible: false,
      auth: '', // 当前用户权限
      ifAuth: false // 是否开启按钮
    }
  },
  mounted() {
    this.getSortAuth()
  },
  methods: {
    showDialog() {
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          this.$refs.ConfirmDialog.setDialogVisible(true)
        } else {
          return false
        }
      })
    },
    setDialogVisible(val) {
      this.dialogVisible = val
    },
    getSortList() {
      sortList(this.sortQueryParams).then(res => {
        this.sortData = res.data.data
        this.getSortArr()
      })
    },
    getSortAuth() {
      sortAuth().then(res => {
        this.auth = res.data.data
        if (res.data.data === 'P_MOBILE_CONSOLE_MAIN_ADMIN' || res.data.data === 'P_MOBILE_CONSOLE_APP_SET_ADMIN') {
          this.ifAuth = true
        } else {
          this.ifAuth = false
        }
      })
    },
    getAppByAppSet(val) {
      const params = {
        appSetId: val
      }
      getAppByAppSet(params).then(res => {
        this.appList = res.data.data
      })
    },
    getSortArr() {
      // 合并所属应用相同的对象生成数组
      const tempObj = {}
      this.sortData.forEach((item) => {
        const { appName } = item
        if (!tempObj[appName]) {
          tempObj[appName] = {
            appName,
            newArr: []
          }
        }
        tempObj[appName].newArr.push(item)
      })
      this.mergeArr = Object.values(tempObj)
      // 合并后的数组的处理后生产一级菜单id数组，二级菜单首位id数组、二级菜单末位id数组

      // 一级菜单id数组
      this.flagArr = []
      // 二级菜单首位id数组
      this.firstArr = []
      // 二级菜单末位id数组
      this.lastArr = []
      this.mergeArr.forEach((item) => {
        this.flagArr.push(item.newArr[0].id)
        if (item.newArr.length === 1) {
          this.firstArr.push('')
          this.lastArr.push('')
        } else if (item.newArr.length === 2) {
          this.firstArr.push(item.newArr[item.newArr.length - 1].id)
          this.lastArr.push(item.newArr[item.newArr.length - 1].id)
        } else {
          this.lastArr.push(item.newArr[item.newArr.length - 1].id)
          this.firstArr.push(item.newArr[1].id)
        }
      })
    },
    validate(val, flag) {
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          if (flag) { this.sortQueryParams.appId = val } else { this.sortQueryParams.appSetId = val }
          this.getSortList()
        } else {
          if (flag) { this.sortQueryParams.appId = val } else { this.sortQueryParams.appSetId = val }
          this.Form.appId = ''
          this.sortQueryParams.appId = this.Form.appId
          this.sortData = []
          return false
        }
      })
    },
    selectChange(val) {
      this.getAppByAppSet(val)
      this.validate(val, 0)
    },
    selectChange1(val) {
      this.validate(val, 1)
    },
    move(row, value) {
      if (value === 1 || value === -1) {
        const index = this.sortData.indexOf(row)
        // 修改数组的sort的值
        // row.sort += value
        // this.sortData[index + value].sort -= value

        // let tempSort = 0
        // tempSort = this.sortData[index].sort
        // this.sortData[index].sort = this.sortData[index + value].sort
        // this.sortData[index + value].sort = tempSort

        // 交换数组位置
        let temp = {}
        temp = this.sortData[index]
        this.sortData[index] = this.sortData[index + value]
        this.sortData[index + value] = temp
        this.getSortArr()
      } else {
        var arrIndex = 0
        this.mergeArr.forEach((item, index) => {
          if (item.newArr.indexOf(row) > -1) {
            arrIndex = index
            return
          }
        })
        // 修改数组的sort的值
        // this.mergeArr[arrIndex].newArr.forEach(item => { item.sort += value })
        // this.mergeArr[arrIndex + value / 100].newArr.forEach(item => { item.sort -= value })

        // 交换数组位置
        let temp = {}
        temp = this.mergeArr[arrIndex]
        this.mergeArr[arrIndex] = this.mergeArr[arrIndex + value / 100]
        this.mergeArr[arrIndex + value / 100] = temp
        var newArr = []
        this.mergeArr.forEach(item => {
          newArr = newArr.concat(item.newArr.flat())
        })
        this.sortData = newArr
      }
      this.$nextTick(() => {
        this.sortData = [...this.sortData]
        this.getSortArr()
      })
    },
    save() {
      //
      // 重新排序
      var count = 0
      var times = 0
      this.mergeArr.forEach(item => {
        item.newArr.forEach(el => {
          el.sort = count
          count++
        })
        times++
        count = times * 100
      })
      var newArr = []
      this.mergeArr.forEach(item => {
        newArr = newArr.concat(item.newArr.flat())
      })
      this.sortData = newArr

      const params = this.sortData.map(item => { return { id: item.id, sort: item.sort } })
      sort(params).then(() => {
        this.dialogVisible = false
      })
    },
    reset() {
      this.$nextTick(() => {
        this.getSortList()
      })
    },
    resetQueryParams() {
      this.$refs.Form.resetFields()
      this.sortQueryParams.appId = ''
      this.sortQueryParams.appSetId = ''
      this.getSortList()
    }
  },

}
</script>

<style lang="scss" scoped>
.tableClass{
    border-top: 1px solid gray;
    padding-top: 20px;
  }
  .search{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-select{
      width: 100%;
    }
  }
  .btn-group{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .common-btn + .common-btn {
    margin-left: 16px;
  }
  .c-blue {
    color: #418CFF;
  }
  .c-gray {
    color: #C0C4CC;
  }
</style>

<style lang="scss">
.dialogClass{
  .el-dialog__headerbtn .el-dialog__close{
    color: #fff;
  }
  .el-dialog__header{
    background-color: rgba(37, 148, 255, 1);
    color: #fff;
  }
  .el-dialog__body{
    padding: 10px 20px;
    .pagination-container{
      padding-bottom: 0;
    }
  }
}
</style>
